/**
 * Created by XianTao on 2016/11/10
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.portal.service;

import lombok.extern.slf4j.Slf4j;
import org.lego.handle.exception.ExtraInvalidParameterException;
import org.lego.util.IpUtil;
import org.lego.wechat.base.entity.WxCorp;
import org.lego.wechat.base.service.WxCorpService;
import org.lego.wechat.portal.WechatPortalApplication;
import org.lego.wechat.portal.configuration.ConstantMessageKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Slf4j
public class WechatPortalService {
    @Autowired
    private WxCorpService wxCorpService;

    public WxCorp getValidWxCorp(String corpId, Integer agentId, HttpServletRequest request) {
        String fromIp = IpUtil.getRealIp(request);
        if (!isWechatIp(corpId, agentId, fromIp)) {
            throw new ExtraInvalidParameterException(ConstantMessageKey.WECHAT_SYSTEM_WRONG_FROM_IP, fromIp);
        }
        return wxCorpService.findOneByCorpIdAndAgentId(corpId, agentId);
    }

    /**
     * 判断请求服务器的ip地址是否是微信的服务器
     *
     * @param corpId  公众号id
     * @param agentId 企业号agent，非企业号默认为0
     * @param fromIp  请求服务器的ip地址
     * @return true:是微信的服务器
     */
    private boolean isWechatIp(String corpId, Integer agentId, String fromIp) {
        log.info("来访ip: {}", fromIp);
        if ("127.0.0.1".equals(fromIp)) {
            return true;
        }
        List<String> wechatIpList = WechatPortalApplication.WECHAT_TRUE_ID_LIST.get(corpId.concat(String.valueOf(agentId)));
        if (!ObjectUtils.isEmpty(wechatIpList)) {
            for (String wechatIp : wechatIpList) {
                if (wechatIp.contains(fromIp)) {
                    return true;
                }
            }
        }
        return false;
    }
}
